import { useState } from 'react'
import { Button, Input, Popconfirm, message } from 'antd'
import PT from 'prop-types'

const TodoItem = function TodoItem(props) {
    // 接收属性 & 定义状态
    let { info, handle } = props
    let [isUpdate, setIsUpdate] = useState(false),
        [updateText, setUpdateText] = useState('')

    // 触发修改状态
    const triggerUpdate = () => {
        setIsUpdate(true)
        setUpdateText(info.text)
    }

    // 取消修改
    const cancelUpdate = () => {
        setIsUpdate(false)
        setUpdateText('')
    }

    // 保存任务
    const saveInfo = () => {
        if (updateText.length === 0) {
            message.warning('修改的任务描述不能为空')
            return
        }
        handle('update', info.id, updateText)
        cancelUpdate()
    }

    // 删除任务
    const removeInfo = () => {
        handle('delete', info.id)
    }

    return <li className="item">
        <p className="text">
            {isUpdate ?
                <Input size="small"
                    value={updateText}
                    onChange={ev => {
                        setUpdateText(ev.target.value.trim())
                    }} /> :
                <span>{info.text}</span>
            }
        </p>
        <p className="handle">
            <Popconfirm title="您确定要删除此任务吗？" onConfirm={removeInfo}>
                <Button type="primary" size="small" danger>删除</Button>
            </Popconfirm>
            {isUpdate ?
                <>
                    <Button type="primary" size="small" onClick={saveInfo}>保存</Button>
                    <Button size="small" onClick={cancelUpdate}>取消</Button>
                </> :
                <Button type="primary" size="small" onClick={triggerUpdate}>修改</Button>
            }
        </p>
    </li>
}
/* 属性规则校验 */
TodoItem.defaultProps = {}
TodoItem.propTypes = {
    info: PT.object.isRequired,
    handle: PT.func.isRequired
}

export default TodoItem